<?php

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Request;
class CooperationController extends Controller
{
    public function getAdviceList(){

        try{
            $results = DB::table('advice')->paginate(10);
//            dd($results);

            return view('Admin.advicelist',['results'=> $results]);

        }catch (Exception $e){

            $info =  $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
            exit;
        }
    }


    public function addAdvice(){

        try{
            $data = Request::only('advice_question', 'advice_answer');

            $validator = Validator::make($data, [
                'advice_question' => 'required',
                'advice_answer' => 'required',
            ]);

            if ($validator->fails()) {
                return $validator->messages();
            }

            $result = DB::table('advice')->insert($data);
            if($result){

                return redirect('/admin/getAdviceList');
            }
        }catch (Exception $e){

            $info =  $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
            exit;
        }
    }

    public function updateAdvice(){

        try{
            $data = Request::only('advice_question', 'advice_answer','advice_id');

            $validator = Validator::make($data, [
                'advice_question' => 'required',
                'advice_answer' => 'required',
                'advice_id' => 'required',
            ]);

            if ($validator->fails()) {
                return $validator->messages();
            }

            $result = DB::table('advice')->where('advice_id','=',$data['advice_id'])->update($data);
            if($result){

                return redirect('/admin/getAdviceList');
            }
        }catch (Exception $e){

            $info =  $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
            exit;
        }
    }

    public function deleteAdvice(){

        try{
            $data = Request::only('advice_id');
            $results = DB::table('advice')->where('advice_id','=',$data['advice_id'])->delete();
            if($results){

                return redirect('/admin/getAdviceList');
            }

        }catch (Exception $e){

            $info =  $e->getMessage().'failed line:'.$e->getLine().'failed string:'.$e->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
            exit;
        }

    }

}
